<?php
namespace Application\Api\Controller;

class WeiXinSpPay extends Base
{

    private function add($userId, $orderNo, $amount, $product)
    {
        $serviceOrder = $this->get(SERVICE_ORDER);
        $now = getDateTime();
        $insert = [
            'dry_user' => $userId,
            'dry_order_no' => $orderNo,
            'dry_amount' => $amount,
            'dry_add_date' => $now['date'],
            'dry_add_time' => $now['date_time'],
            'dry_status' => ORDER_STATUS_NO_PAY,
            'dry_type' => PAY_TYPE_WEIXIN_SP,
            'dry_product_id' => $product->id,
            'dry_product_raw' => json_encode($product),
            'dry_pay_raw' => '',
            'dry_note' => ''
        ];
        return $serviceOrder->add($insert);
    }

    /*
        /Api/WeiXinSpPay/getPay
    */
    public function getPayAction()
    {
        $data = $this->getRequestData();
        if(notSetOrEmpty($data, 'token') || notSetOrEmpty($data, 'openid')){
            $this->sendFail('TOKEN_ERROR', '', __LINE__);
            return false;
        }
        if(notSetOrEmpty($data, 'id')){
            $this->sendFail('FAIL', '请选择一个产品', __LINE__);
            return false;
        }
        $device = DEVICE_WEIXIN_SP;
        $token = $data['token'];
        $openId = $data['openid'];
        $id = $data['id'];
        $code = tryGet($data, 'code', '');
        $product = $this->get(SERVICE_PRODUCT)->one($id);
        if(empty($product)){
            $this->sendFail('FAIL', '请选择一个产品', __LINE__);
            return false;
        }
        $serviceUser = $this->get(SERVICE_USER);
        $result = $serviceUser->validToken($device, $token);
        if(!$result){
            $this->sendFail('TOKEN_ERROR', '', __LINE__);
            return false;
        }
        $userId = $result['id'];
        $mainProduct = $product->dry_main_product;
        $orderNo = makeOrderNo($userId, PAY_TYPE_WEIXIN_SP);
        $price = $product->dry_price;

        /*已经买过 start*/
        $agent = $this->get(SERVICE_PRODUCTAGENT)->hasAgent($userId, $mainProduct, $product->dry_main_product_spec);
        if($agent){
            $this->sendFail('FAIL', '无需再次购买');
            return false;
        }
        /*已经买过 end*/

        /*优惠码 start*/
        if(!empty($code) && $product->dry_is_use_code == '1'){
            $codeUserId = (int)parseUserCode($code);
            if($codeUserId > 0){
                $serviceProductAgent = $this->get(SERVICE_PRODUCTAGENT);
                $discount = $serviceProductAgent->getDiscount($codeUserId, $mainProduct);
                $price = bcsub($price, $discount, 2);
                if($price <= 0){
                    $price = $product->dry_price;
                }
                $product->code = $code;
                $product->codeUserId = $codeUserId;
                $product->codeDiscount = $discount;
            }
        }
        /*优惠码 end*/

        /*订单入库 start*/
        $this->add($userId, $orderNo, $price, $product);
        /*订单入库 end*/

        /*任务入库 start*/
        $domain = getDomain();
        $dateTime = getDateTime();
        $endTime = getDateTimeStd(getTimestamp() + 900);
        $theData = [
            'order_no' => $orderNo
        ];
        $this->get(SERVICE_SYSTEMTASK)->addTask('wei_xin_sp_order_check', "{$domain}/Api/SystemTask/weiXinSpOrderCheck", 0, 10, $dateTime['date_time'], $endTime, 5, json_encode($theData));
        /*任务入库 end*/

        /*任务入库 start*/
        $startTime = getDateTimeStd(getTimestamp() + 900);
        $endTime = getDateTimeStd(getTimestamp() + 1800);
        $this->get(SERVICE_SYSTEMTASK)->addTask('wei_xin_sp_order_cancel', "{$domain}/Api/SystemTask/weiXinSpOrderCancel", 0, 10, $startTime, $endTime, 5, json_encode($theData));
        /*任务入库 end*/

        $result = $this->get(PAY_WEIXINSP)->getPay($openId, $product->dry_name, $orderNo, $price);
        $this->sendSuccess($result);
    }

}